package com.teziyou.commodity.web;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.teziyou.commodity.util.DateUtil;
import com.teziyou.commodity.util.IDUtil;
import com.teziyou.commodity.util.Maps;
import com.teziyou.commodity.util.PropUtil;

@RequestMapping("/common")
@Controller
public class CommonController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CommonController.class);
	
	@ResponseBody
	@RequestMapping("/upload")
	public String upload(HttpServletRequest req) {
		//如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解  
        //如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解  
        //并且上传多个文件时，前台表单中的所有<input type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件
		String type = req.getParameter("type");
		type = StringUtils.isBlank(type)?"common":type;
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
		MultipartFile mf = multipartRequest.getFile("file");
		String fileName = mf.getOriginalFilename();
		String suffix = fileName.split("\\.")[1];
		
		//String rootPath = req.getSession().getServletContext().getRealPath("/");
		String middlePath = PropUtil.get("save_path")+type+"/"+DateUtil.formatDate(new Date(), "yyyyMMdd");
		String directoryPath = middlePath;
		File file = new File(directoryPath);
		try {
			if(!file.exists()) file.mkdirs();
			String endPath = "/"+IDUtil.getId()+"."+suffix;
			File newFile = new File(directoryPath+endPath);
			if(!newFile.exists()) newFile.createNewFile();
			mf.transferTo(newFile);
			//TODO 存个100*100缩略图
			String fullPath = middlePath+endPath;
			logger.info(fullPath);
			logger.info(fullPath.substring(12, fullPath.length()));
			return success(null, Maps.newHashMap("url", fullPath.substring(12, fullPath.length())));
		} catch (IOException e) {
			logger.error(e);
			return fail("上传文件失败！！");
		}
	}

}


/**
 * //	@RequestMapping("/upload")
//	public String upload(HttpServletRequest req) {
 *		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
//		Map<String, MultipartFile> map = multipartRequest.getFileMap();
//		for(Map.Entry<String, MultipartFile> entry:map.entrySet()) {
//			System.err.println(entry.getKey());
//			System.err.println(entry.getValue().getOriginalFilename());
//		}
 */
